package com.example.clock.lockedPage;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
import static com.example.clock.R.id.imageButton;
import static com.example.clock.R.id.imageButton10;
import static com.example.clock.R.id.imageButton3;
import static com.example.clock.R.id.imageButton4;
import static com.example.clock.R.id.spinner3;
import static com.example.clock.R.id.textView6;
import static com.example.clock.controlClass.SqlController.ForceUnlockTime;
import static com.example.clock.controlClass.SqlController.addTask;
import static com.example.clock.controlClass.SqlController.changePlanByTimeAndTimes;
import static com.example.clock.controlClass.SqlController.getTodayString;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;


import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.Image;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.clock.R;
import com.example.clock.basicClass.Task;
import com.example.clock.controlClass.DatabaseHelper;

import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

public class LockActivity extends AppCompatActivity {

    public Task task = new Task();

    private String taskId;//唯一标识
    private String taskName;//名字
    private String tips;//备注
    private String date;//执行日期xxxx-xx-xx
    private String startTime;//开始时间00:00:00
    private String endTime;//结束时间00:00:00
    private int lastTime;//持续时间（分钟）
    private int planTime;//计划持续时间（分钟）
    private String largeTags;//大标签
    private String smallTags;//小标签
    private String planId;//所绑定的计划planId
    private boolean clockedTask;//本次事件是否是锁屏，true代表是，false代表不是
    private int clockedMode;//1，2，3分别代表简单，困难，地狱模式
    private int unlocked;//本次锁屏是否中途解锁结束，0是没有，1是中途解锁了，2是强制解锁

    //Local usage
    private int timeleft; //锁屏时长
    private TextView tvCountdown;  //显示剩余时间
    private CountDownTimer countDownTimer;
    private long timeLeftInMillis;
    private PopupWindow mPopWindow;
    private boolean lockFinished = false;
    private boolean timeDisplayStyle = false;
    private boolean lockClass;  //锁屏类型
    private int lockRemaining;  //从数据库获取
    private Date dateNow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lock);

        //Note:由于新版android操作系统不会将点击Home键事件传递给应用APP，因此无法直接屏蔽Home键
        //解决方案：提示用户Home键可在紧急情况下使用，但是已锁屏时间将被清零，请慎用
        //用户在点击Home键后，应用程序将进入后台，通过检测应用程序是否在前后台运行，详见isAppInForeground()
        //如果是在后台运行，则不会保留已锁屏时间
        Toast.makeText(getApplicationContext(), "温馨提示：锁屏期间手机导航键区域的返回键和任务键暂时不能使用；" +
                "主页键可在紧急情况下使用，但是已锁屏时间将被清零，请慎用。", Toast.LENGTH_LONG).show();


        tvCountdown = findViewById(R.id.textView9);//倒计时显示区域

        //从数据库获取强制解锁剩余次数 lockRemaining
        DatabaseHelper dbhelper = new DatabaseHelper(LockActivity.this,LockActivity.this);
        SQLiteDatabase db = dbhelper.getReadableDatabase();
        Cursor c = db.query("unlockedSetting",null,null,null,null,null,null);
        c.moveToFirst();
        @SuppressLint("Range") int times = Integer.parseInt(c.getString(c.getColumnIndex("forceUnclockTime")));
        lockRemaining = times;

        System.out.println("lockremaining="+lockRemaining);

        task=(Task) getIntent().getSerializableExtra("Serializable");

        //通过Serializable方法获取设置界面传送来的锁屏配置数据
//        Transport transport1 = (Transport) getIntent().getSerializableExtra("Serializable");
        timeleft = task.getPlanTime();//计划锁屏时长
//        lockClass = transport1.getType();
        lockClass =(task.getClockedMode()==2);
        planId = task.getPlanId();

        TextView primaryclass = (TextView) findViewById(R.id.textView13);
        primaryclass.setText(task.getLargeTags());//一级事件
        TextView secondaryclass = (TextView) findViewById(R.id.textView14);
        secondaryclass.setText(task.getSmallTags());//二级事件
        TextView locknote = (TextView) findViewById(R.id.textView15);
        locknote.setText(task.getTips());//备注
        locknote.setTextColor(Color.GRAY);
        TextView taskName = (TextView) findViewById(R.id.textView16);
        taskName.setText("事件名：" + task.getTaskName());//

        //组装task静态数据
        //task.setTaskId(null);  由于taskID是在数据库中自动生成，故不用设置

        Date date = new Date();
        dateNow = date;
        String day = String.format("%tF", date);
        task.setDate(day);
        String nowtime = String.format("%tT", date);
        task.setStartTime(nowtime);

//        task.setPlanTime(timeleft);
//        task.setLargeTags(transport1.getPc());
//        task.setSmallTags(transport1.getSc());
//        task.setPlanId("0");//planid承接调用者

        task.setClockedTask(1);
        if (lockClass==false) {task.setClockedMode(1);}
        else {task.setClockedMode(2);}
        //组装task静态数据结束

        //倒计时
        int hour = timeleft / 60;
        int minute = timeleft - hour * 60;
        startCountdown(hour, minute);

    }



    //判断app是否在前台运行
    private boolean isAppInForeground() {
        boolean isInForeground=false;
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfoList = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : processInfoList) {
            if (processInfo.processName.startsWith("com.example.clock")) {
                isInForeground =  processInfo.importance == IMPORTANCE_FOREGROUND;
                break;
            }
        }
        return isInForeground;
    }

    public static void setTopApp(Context context) {

            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            //获得当前运行的task(任务)
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(50);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                //Log.e("MainActivity", "进程Task：" + taskInfo.topActivity.getPackageName());
                //找到本应用的 task，并将它切换到前台
                if (taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
                    activityManager.moveTaskToFront(taskInfo.id, 0);
                    break;
                }
            }

    }


    //屏蔽导航键区域的任务键
    @Override
    protected void onPause() {
        super.onPause();
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.moveTaskToFront(getTaskId(), 0);

        Toast.makeText(this, "禁止离开前台", Toast.LENGTH_SHORT).show();

    }



    //屏蔽导航键区域的返回键
    @Override
    public void onBackPressed() {
        Toast.makeText(getApplicationContext(), "温馨提示：锁屏期间手机导航键区域的返回键和任务键暂时不能使用；" +
                "主页键可在紧急情况下使用，但是已锁屏时间将被清零，请慎用。", Toast.LENGTH_LONG).show();
    }

    //屏幕顶部箭头键处理
    public void onClickArrow(View view){

        if (!lockFinished) {
            if (lockClass == true) { //读取并判断锁屏类型
                Toast.makeText(LockActivity.this, "已经是严格模式，不能升级", Toast.LENGTH_SHORT).show();
            } else {
                upgradeConfirm();  //锁屏类型升级处理
            }
        }
        else{
            TextView lockend;
            lockend = findViewById(R.id.textView6);
            lockend.setText(String.format("锁屏结束,请按解锁键返回"));
        }
    }


    //屏幕顶部解锁键处理
    public void onClickLock(View view){



        if (!lockFinished ){

            if (lockClass == false)  //读取并判断锁屏类型
            {
                //简单模式，直接解锁
                //组装task数据，并保存到数据库

                Date date = new Date();
                String endingtime = String.format("%tT", date);
                task.setEndTime(endingtime);
                long begin,end;
                end = date.getTime();
                begin = dateNow.getTime();
                long timeLag = end - begin;
                int lastTimeInMunites = (int) timeLag/1000/60;
                if (lastTimeInMunites==0){lastTimeInMunites=1;}
                task.setLastTime(lastTimeInMunites);

                task.setClockedMode(1);
                task.setUnlocked(1);

                TextView tips = (TextView) findViewById(R.id.textView15);//获取锁屏备注参数字符串
                task.setTips(tips.getText().toString());

                DatabaseHelper dbhelper = new DatabaseHelper(LockActivity.this,LockActivity.this);
                SQLiteDatabase db = dbhelper.getReadableDatabase();

                addTask(db,task);
                changePlanByTimeAndTimes(db,planId,false,lastTimeInMunites);
                finish();
            }

            else {
                if (lockRemaining>0) {
                    unlockConfirm();  //强制解锁确认或取消处理
                }
                else{
                    Toast.makeText(LockActivity.this, "本月强制解锁额度已用完，不能强制解锁", Toast.LENGTH_SHORT).show();}
            }

        }
        else{
            //锁屏正常结束
            //组装task数据，并保存到数据库
            Date date = new Date();
            String endingtime = String.format("%tT", date);
            task.setEndTime(endingtime);
            long begin,end;
            end = date.getTime();
            begin = dateNow.getTime();
            long timeLag = end - begin;
            int lastTimeInMunites = (int) timeLag/1000/60;
            if (lastTimeInMunites==0){lastTimeInMunites=1;}
            task.setLastTime(lastTimeInMunites);

            if (lockClass==false) {task.setClockedMode(1);}
            else {task.setClockedMode(2);}
            task.setUnlocked(0);

            TextView tips = (TextView) findViewById(R.id.textView15);//获取锁屏备注参数字符串
            task.setTips(tips.getText().toString());

            DatabaseHelper dbhelper = new DatabaseHelper(LockActivity.this,LockActivity.this);
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            addTask(db,task);
            changePlanByTimeAndTimes(db,planId,true,lastTimeInMunites);
            finish();
        }


    }

    //屏幕顶部三点键处理
    public void onClickThreePoint(View view){

        //显示事件信息
        View layout = findViewById(R.id.constraintLayout);
        layout.setVisibility(View.VISIBLE);

    }

    //task框内右上部X键处理
    public void onClickCross(View view) {

        //隐藏事件信息
        View layout = findViewById(R.id.constraintLayout);
        layout.setVisibility(View.INVISIBLE);

    }

    //锁屏时间显示切换按钮处理
    public void onClickChangeStyle(View view){
        timeDisplayStyle = !timeDisplayStyle;
    }

    private void startCountdown(int hour, int minute) {
        // 计算剩余时间的毫秒数
        timeLeftInMillis = (hour * 60 + minute) * 60 * 1000;


        // 开始倒计时
        countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
            @Override
            //每个一秒执行锁屏时间更新
            public void onTick(long millisUntilFinished) {
                if (isAppInForeground()) {   //判断是否在前台运行
                    timeLeftInMillis = millisUntilFinished;
                    updateCountdownText();
                }
                else {

                    setTopApp(LockActivity.this);//将应用强制放回到前台
                    timeLeftInMillis = millisUntilFinished;
                    updateCountdownText();
                    //finish();//用户点击Home键，直接退出锁屏界面，已锁屏时间不予保留
                }
            }

            @Override
            public void onFinish() {  //倒计时结束时的处理
                TextView lockend;
                lockend = findViewById(R.id.textView6);
                lockend.setText(String.format("锁屏结束,请按解锁键返回"));
                tvCountdown.setText(String.format("剩余时间: %02d:%02d:%02d ", 0, 0, 0));
                lockFinished = true;   //设置锁屏已结束标志
            }

        }.start();
    }

    //显示倒计时
    private void updateCountdownText() {
        int hours = (int) (timeLeftInMillis / 1000 / 3600);
        int minutes = (int) ((timeLeftInMillis / 1000) % 3600 / 60);
        int seconds = (int) (timeLeftInMillis / 1000 % 60);

        int pastHours = (int) ((timeleft*60*1000 -timeLeftInMillis )/1000/3600);
        int pastMinutes = (int) ((((timeleft * 60 * 1000 - timeLeftInMillis) / 1000) % 3600) / 60);
        int pastSeconds = (int) (60 - seconds);
        if (pastSeconds == 60) {
            pastSeconds = 0;
            pastMinutes = pastMinutes + 1;
        }

        //根据用户选择显示锁屏时间或锁屏倒计时
        if (timeDisplayStyle) {
            tvCountdown.setText(String.format("锁屏倒计时: %02d:%02d:%02d ", hours, minutes, seconds));
        } else {
            tvCountdown.setText(String.format("锁屏时间: %02d:%02d:%02d ", pastHours, pastMinutes, pastSeconds));
        }
    }


    //锁屏类型升级处理
    private void upgradeConfirm(){
        //获取自定义view
        View mDialogView = LayoutInflater.from(this).inflate(R.layout.upgrade_confirm, null);
        mPopWindow = new PopupWindow(mDialogView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, false);
        mPopWindow.setOutsideTouchable(false);
        //显示弹窗
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_lock, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER,0, 0);

        //弹窗以外界面变灰
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);

        //设置弹窗提示
        int timeLeftHours = (int) (timeLeftInMillis / 1000 / 3600);
        int timeLeftMinutes = (int) ((timeLeftInMillis / 1000) % 3600 / 60);
        //TextView tv=(TextView)mPopWindow.getContentView().findViewById(R.id.textView23);
        TextView tv=(TextView)mDialogView.findViewById(R.id.textView23);
        if(timeLeftHours>0) {
            tv.setText("     接下来将升级到需要等待" + timeLeftHours + "小时" + timeLeftMinutes + "分钟后解锁，请确认没有紧急事件后再升级");
        }
        else{
            tv.setText("     接下来将升级到需要等待"+ timeLeftMinutes + "分钟后解锁，请确认没有紧急事件后再升级");
        }
        tv.setTextColor(Color.BLACK);

        //取消升级按钮处理
        Button bt_cancel=(Button)mDialogView.findViewById(R.id.button3);
        bt_cancel.setBackgroundColor(Color.YELLOW);
        bt_cancel.setTextColor(Color.BLACK);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();//关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });

        //确定升级按钮处理
        Button bt_ok=(Button)mDialogView.findViewById(R.id.button2);
        bt_ok.setBackgroundColor(Color.CYAN);
        bt_ok.setTextColor(Color.BLACK);
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lockClass = true;  //锁屏升级
                mPopWindow.dismiss();  //关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
    }


    private void unlockConfirm(){
        //获取自定义view
        View mDialogView = LayoutInflater.from(this).inflate(R.layout.unlock_confirm, null);
        mPopWindow = new PopupWindow(mDialogView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, false);
        mPopWindow.setOutsideTouchable(false);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_lock, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER,0, 0);

        //弹窗以外界面变灰
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);

        //设置弹窗提示
        TextView tv=(TextView)mPopWindow.getContentView().findViewById(R.id.textView20);

        tv.setText("      强制解锁本月还剩余" + lockRemaining + "次机会，您确定要强制结束?");
        tv.setTextColor(Color.BLACK);
        tv.setTextSize(18);


        //取消解锁按钮处理
        Button bt_cancel=(Button)mDialogView.findViewById(R.id.button5);
        bt_cancel.setBackgroundColor(Color.YELLOW);
        bt_cancel.setTextColor(Color.BLACK);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();  //关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });

        //确定升级按钮处理
        Button bt_ok=(Button)mDialogView.findViewById(R.id.button4);
        bt_ok.setBackgroundColor(Color.CYAN);
        bt_ok.setTextColor(Color.BLACK);
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //lockRemaining 次数减 1，并保存到数据库
                DatabaseHelper dbhelper = new DatabaseHelper(LockActivity.this,LockActivity.this);
                SQLiteDatabase db = dbhelper.getReadableDatabase();
                Cursor c = db.query("unlockedSetting",null,null,null,null,null,null);
                c.moveToFirst();
                @SuppressLint("Range") int times = Integer.parseInt(c.getString(c.getColumnIndex("forceUnclockTime")));
                times--;
                ContentValues cv = new ContentValues();
                cv.put("forceUnclockTime",times);
                db.update("unlockedSetting",cv,null,null);

                //组装task数据，并保存到数据库
                Date date = new Date();
                String endingtime = String.format("%tT", date);
                task.setEndTime(endingtime);
                long begin,end;
                end = date.getTime();
                begin = dateNow.getTime();
                long timeLag = end - begin;
                int lastTimeInMunites = (int) timeLag/1000/60;
                if (lastTimeInMunites==0){lastTimeInMunites=1;}
                task.setLastTime(lastTimeInMunites);

                task.setClockedMode(2);
                task.setUnlocked(2);

                TextView tips = (TextView) findViewById(R.id.textView15);//获取锁屏备注参数字符串
                task.setTips(tips.getText().toString());

                addTask(db,task);
                changePlanByTimeAndTimes(db,planId,false,lastTimeInMunites);
                mPopWindow.dismiss();  //关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);

                finish();//退出锁屏界面
            }
        });
    }


}
